import {
  deleteCommentUsingPost,
  listCommentByPageUsingPost,
} from '@/services/backend/commentController';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Image, message, Space, Typography } from 'antd';
import React, { useRef, useState } from 'react';
import { history } from 'umi';
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Comment>();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.Comment) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteCommentUsingPost({
        id: row.id,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  const typeEnumMap = new Map([
    ['post', '帖子'],
    ['project', '项目'],
    ['service', '服务'],
  ]);

  const columns: ProColumns<API.Comment>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '目标ID',
      dataIndex: 'targetId',
      valueType: 'text',
      hideInForm: true,
      render: (_, entity) => {
        return (
          <Typography.Link
            onClick={() => {
              switch (entity.type) {
                case 'post':
                  history.push(`/admin/post?id=${entity.targetId}`);
                  break;
                case 'project':
                  history.push(`/admin/bisheProject?id=${entity.targetId}`);
                  break;
                case 'service':
                  history.push(`/admin/service?id=${entity.targetId}`);
                  break;
              }
            }}
          >
            {entity.targetId}
          </Typography.Link>
        );
      },
    },
    {
      title: '评论类型',
      dataIndex: 'type',
      valueType: 'select',
      valueEnum: typeEnumMap,
      hideInForm: true,
    },
    {
      title: '评论用户ID',
      dataIndex: 'userId',
      valueType: 'text',
      hideInForm: true,
      render: (_, entity) => {
        return (
          <Typography.Link
            onClick={() => {
              history.push(`/admin/user?id=${entity.userId}`);
            }}
          >
            {entity.userId}
          </Typography.Link>
        );
      },
    },
    {
      title: '父评论ID',
      dataIndex: 'parentId',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '评论内容',
      dataIndex: 'content',
      valueType: 'text',
      ellipsis: true,
      tooltip: { title: '省略过长内容' },
    },
    {
      title: '图片列表',
      dataIndex: 'pictureList',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
      render: (_, entity) => {
        return (
          <Space size={4}>
            {entity.pictureList?.map((item) => (
              <Image key={item} src={item} width={60} />
            ))}
          </Space>
        );
      },
    },
    {
      title: '点赞数',
      dataIndex: 'thumbNum',
      valueType: 'digit',
      width: 80,
      hideInSearch: true,
      hideInForm: true,
    },

    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size={'middle'}>
          <Typography.Link
            key="config"
            onClick={() => {
              setUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link
            type="danger"
            onClick={() => {
              handleDelete(record);
            }}
          >
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.Comment>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listCommentByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.CommentQueryRequest);
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      {/*新增悬浮窗*/}
      <CreateModal
        modalVisible={createModalVisible}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      {/*更新悬浮窗*/}
      <UpdateModal
        oldData={currentRow}
        modalVisible={updateModalVisible}
        columns={columns}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default TableList;
